<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item
        label="行程库名称"
        prop="itineraryName"
        
      >
        <el-input
          v-model="queryParams.itineraryName"
          placeholder="请输入行程库名称"
          clearable
          @keyup.enter.native="handleQuery"
          :disabled="isitineraryDisabled"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
          :disabled="isCreateByDisabled"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['travel:itinerary:add']"
          v-if="showAddButton()"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['travel:itinerary:edit']"
          v-if="showEditButton()"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['travel:itinerary:remove']"
          v-if="showDeleteButton()"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 行程库表格 -->
    <!-- 行程库表格 -->
    <el-table
      v-loading="loading"
      :data="itineraryList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="序号" align="center" prop="itineraryId" />-->
      <el-table-column label="序号" align="center">
        <template slot-scope="scope">
          <!-- 公式：(当前页-1) * 每页条数 + 当前行索引 + 1 -->
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="行程库名称" align="center" prop="itineraryName" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="showEditButton()"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="showDeleteButton()"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-if="showDetailButton()"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改/详情对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="dialogForm" :rules="rules" label-width="80px">
        <!-- 行程库名称 -->
        <el-row :gutter="15" class="mb8">
          <el-col :span="24">
            <el-form-item
              label="行程库名称"
              prop="itineraryName"
              label-width="100px"
            >
              <el-input
                v-model="dialogForm.itineraryName"
                placeholder="请输入行程库名称"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 动态行程内容区域 -->
        <div class="dynamic-content-wrapper">
          <div
            v-for="(content, index) in dialogForm.itineraryContents"
            :key="content.itineraryContentId || index"
            class="content-item"
            :id="'content-' + index"
          >
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top: 15px;
              "
            >
              <h3 style="margin: 5px 0">内容{{ index + 1 }}</h3>
            </div>

            <!-- 时间设置 -->
            <el-row :gutter="10" class="mb4">
              <el-col :span="10">
                <el-form-item
                  label="经历时间"
                  :prop="
                    'itineraryContents[' + index + '].travelDurationNumber'
                  "
                  :rules="[
                    {
                      required: true,
                      message: '请输入时间数值',
                      trigger: 'blur',
                    },
                    {
                      type: 'number',
                      min: 0,
                      message: '时间不能为负数',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input
                    v-model.number="content.travelDurationNumber"
                    placeholder="请输入时间数值"
                    type="number"
                    min="0"
                    step="0.1"
                    :disabled="isDetailMode"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item
                  label="时间单位"
                  :prop="'itineraryContents[' + index + '].travelDurationUnit'"
                  :rules="[
                    {
                      required: true,
                      message: '请选择时间单位',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-select
                    v-model="content.travelDurationUnit"
                    placeholder="请选择时间单位"
                    :disabled="isDetailMode"
                  >
                    <el-option label="天" value="天" />
                    <el-option label="小时" value="时" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 行程内容描述 -->
            <el-form-item
              label="行程内容"
              :prop="'itineraryContents[' + index + '].itineraryContent'"
              :rules="[
                { required: true, message: '请输入行程内容', trigger: 'blur' },
              ]"
            >
              <el-input
                v-model="content.itineraryContent"
                type="textarea"
                rows="3"
                placeholder="请输入详细行程内容"
                :disabled="isDetailMode"
              />
            </el-form-item>

            <!-- 图片上传 -->
            <el-form-item label="上传图片">
              <el-row :gutter="10">
                <el-col :span="7">
                  <el-upload
                    class="avatar-uploader"
                    action="/dev-api/common/upload"
                    :show-file-list="false"
                    :on-success="
                      (response) => handleImageSuccess(response, index, 1)
                    "
                    :before-upload="beforeImageUpload"
                    :disabled="isDetailMode"
                  >
                    <img
                      v-if="content.picture1"
                      :src="content.picture1"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-col>
                <el-col :span="8">
                  <el-upload
                    class="avatar-uploader"
                    action="/dev-api/common/upload"
                    :show-file-list="false"
                    :on-success="
                      (response) => handleImageSuccess(response, index, 2)
                    "
                    :before-upload="beforeImageUpload"
                    :disabled="isDetailMode"
                  >
                    <img
                      v-if="content.picture2"
                      :src="content.picture2"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-col>
                <el-col :span="7">
                  <el-upload
                    class="avatar-uploader"
                    action="/dev-api/common/upload"
                    :show-file-list="false"
                    :on-success="
                      (response) => handleImageSuccess(response, index, 3)
                    "
                    :before-upload="beforeImageUpload"
                    :disabled="isDetailMode"
                  >
                    <img
                      v-if="content.picture3"
                      :src="content.picture3"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>

            <!-- 备注信息 -->
            <el-form-item
              label="备注"
              :prop="'itineraryContents[' + index + '].remark'"
            >
              <el-input
                v-model="content.remark"
                type="textarea"
                rows="2"
                placeholder="请输入备注信息"
                :disabled="isDetailMode"
              />
            </el-form-item>

            <!-- 内容操作按钮 -->
            <div class="content-actions">
              <!-- 删除按钮 -->
              <el-button
                v-if="
                  dialogForm.itineraryContents.length > 1 &&
                  index !== dialogForm.itineraryContents.length - 1
                "
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteContent(index)"
                :disabled="isDetailMode"
                >删除内容
              </el-button>

              <!-- 添加按钮 -->
              <el-button
                v-else-if="index === dialogForm.itineraryContents.length - 1"
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="addNewContent()"
                :disabled="isDetailMode || !isContentValid(index)"
                >添加内容
              </el-button>
            </div>

            <hr v-if="index !== dialogForm.itineraryContents.length - 1" />
          </div>
        </div>
      </el-form>

      <!-- 对话框底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDialogForm" v-if="!isDetailMode"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listItinerary,
  getItinerary,
  delItinerary,
  addItinerary,
  updateItinerary,
  getItineraryContent, // 确保导入正确
  batchSaveItineraryContent,
  delAllItineraryContent,
} from "@/api/travel/itinerary";
import { getUserProfile } from "@/api/system/user";
import { getUser } from "@/api/system/user";
export default {
  name: "Itinerary",
  data() {
    return {
      currentUserId: null,
      currentUserRoleName: '',
      // 遮罩层
      loading: true,
      // 选中的ID数组
      ids: [],
      // 单个选中状态
      single: true,
      // 多个选中状态
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总记录数
      total: 0,
      // 行程库列表数据
      itineraryList: [],
      // 对话框标题
      title: "",
      // 对话框显示状态
      open: false,
      // 是否为详情模式
      isDetailMode: false,
      // 当前登录用户信息
      currentUser: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itineraryName: null,
        createBy: null,
        userId: this.currentUserId,
        userRoleName: this.currentUserRoleName,
      },
      // 表单数据
      dialogForm: {
        itineraryId: null,
        itineraryName: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null,
        remark: null,
        isDeleted: 0,
        itineraryContents: [
          {
            itineraryContentId: null,
            itineraryId: null,
            itineraryContentName: "1", // 修正为字符串类型
            travelDurationNumber: null,
            travelDurationUnit: null,
            itineraryContent: null,
            picture1: null,
            picture2: null,
            picture3: null,
            remark: null,
          },
        ],
      },
      // 表单校验规则
      rules: {
        itineraryName: [
          { required: true, message: "行程库名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    // 是否禁用创建人输入框
    isCreateByDisabled() {
      const role = this.currentUserRoleName;
      return role !== '超级管理员';
    },
    // 是否禁用行程库名称输入框
    isitineraryDisabled() {
      const role = this.currentUserRoleName;
      return role !== '超级管理员' && role !== '定制师';
    }
  },
  created() {
    // this.getList();
    this.getUserInfo();
    this.getUserInfo1()
  },

  methods: {
    // 哪种角色可以看到开始按钮
    showAddButton() {
      const role = this.currentUserRoleName
      if (role === '超级管理员') {
        return true
      }
      if (role === '定制师') {
        return true
      }
      return false
    },
    showEditButton() {
      const role = this.currentUserRoleName
      if (role === '超级管理员') {
        return true
      }
      if (role === '定制师') {
        return true
      }
      return false
    },
    showDeleteButton() {
      const role = this.currentUserRoleName
      if (role === '超级管理员') {
        return true
      }
      if (role === '定制师') {
        return true
      }
      return false
    },
    showDetailButton() {
      const role = this.currentUserRoleName
      if (role === '超级管理员') {
        return true
      }
      if (role === '定制师') {
        return true
      }
      return false
    },
    /** 获取行程库列表 */
    getList() {
      // 如果当前用户是“定制师”，且没输入创建人，则默认查自己
      if (this.currentUserRoleName === '定制师' && !this.queryParams.createBy) {
        this.queryParams.createBy = this.currentUser?.userName || this.currentUserId;
      }
      this.loading = true;
      listItinerary(this.queryParams)
        .then((response) => {
          // 过滤null值，确保数据安全
          console.log("后端返回的完整数据：", response);
          this.itineraryList = (response.rows || []).filter(
            (item) => item !== null
          );
          this.total = response.total || 0;
          this.loading = false;
          console.log("后端返回的数据:", response);
        })
        .catch((error) => {
          console.error("获取行程库列表失败:", error);
          this.loading = false;
        });
    },

    /** 获取当前用户信息 */
    getUserInfo() {
      getUserProfile()
        .then((response) => {
          this.currentUser = response.data || { userName: "system" };
        })
        .catch((error) => {
          console.error("获取用户信息失败:", error);
          this.currentUser = { userName: "system" };
        });
    },

    //获取用户信息
    getUserInfo1() {
      try {
        getUserProfile().then(userProfileRes => {
          // 1.保存当前用户的 userId
          this.currentUserId = userProfileRes.data.userId
          this.currentUserRoleName = userProfileRes.data.roles[0].roleName
          // 2. 给 queryParams 赋值
          this.queryParams.userId = this.currentUserId
          this.queryParams.userRoleName = this.currentUserRoleName
          // 3. 调用 getList 加载数据
          this.getList()
        })
      } catch (error) {
        console.error('获取当前用户信息失败：', error)
        this.$message.error('获取用户信息失败，请刷新页面重试')
      }
    },

    /** 搜索按钮事件 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置搜索条件 */
    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields();
      }
      this.handleQuery();
    },

    /** 选择表格数据事件 */
    handleSelectionChange(selection) {
      debugger;
      this.ids = selection.map((item) => item.itineraryId);
      console.log(this.ids);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮事件 */
    handleAdd() {
      this.resetDialogForm();
      this.open = true;
      this.title = "添加行程库";
      this.isDetailMode = false;
    },

    /** 详情按钮事件 */
    handleDetail(row) {
      this.resetDialogForm();
      this.isDetailMode = true;
      this.title = "行程库详情";
      this.loadItineraryDetail(row.itineraryId);
    },

    /** 修改按钮事件 */
    handleUpdate(row) {
      this.resetDialogForm();
      this.isDetailMode = false;
      // 处理选中行ID（兼容表格行点击和顶部修改按钮）
      const itineraryId =
        row?.itineraryId || (this.ids.length ? this.ids[0] : null);

      if (!itineraryId) {
        this.$message.warning("请选择一条行程库记录");
        return;
      }

      this.title = "修改行程库";
      // 加载详情并强制打开对话框（确保数据加载后显示）
      this.loadItineraryDetail(itineraryId)
        .then(() => {
          this.open = true; // 数据加载成功后再显示对话框
        })
        .catch(() => {
          this.open = false;
        });
    },
    // handleUpdate(row) {
    //   this.resetDialogForm();
    //   this.isDetailMode = false;
    //   const itineraryId = row.itineraryId || this.ids;

    //   if (!itineraryId) {
    //     this.$message.warning("请选择一条行程库记录");
    //     return;
    //   }

    //   this.title = "修改行程库";
    //   this.loadItineraryDetail(itineraryId);
    // },

    /** 加载行程库详情 */
    /** 加载行程库详情（借鉴行程管理的回显逻辑） */
    async loadItineraryDetail(itineraryId) {
      try {
        this.loading = true;
        // 1. 获取主行程库信息（对应行程管理的getScheduleDetail）
        const mainRes = await getItinerary(itineraryId);
        const mainData = mainRes.data || {};
        console.log("主表数据（行程库基本信息）：", mainData);

        // 2. 获取行程内容列表（对应行程管理的getContent）
        const contentRes = await getItineraryContent(itineraryId);
        console.log("行程内容接口返回完整数据：", contentRes);
        // 关键：明确数据路径，与后端返回格式严格匹配（参考行程管理的contentRes.data）
        const contentList = contentRes.data || []; // 直接取data，而非data.data（根据实际接口调整）

        // 3. 格式化内容列表（核心：字段严格映射，与表单v-model对应）
        const formattedContents = contentList.map((item, index) => ({
          itineraryContentId: item.itineraryContentId || null, // 对应表单的content.itineraryContentId
          itineraryId: item.itineraryId || itineraryId, // 关联当前行程库ID
          itineraryContentName: (index + 1).toString(), // 序号（1,2,3...）
          travelDurationNumber: Number(item.travelDurationNumber) || null, // 数字类型转换
          travelDurationUnit: item.travelDurationUnit || null, // 对应表单的travelDurationUnit
          itineraryContent: item.itineraryContent || "", // 对应表单的行程描述
          picture1: item.picture1 || null,
          picture2: item.picture2 || null,
          picture3: item.picture3 || null,
          remark: item.remark || "",
        }));
        console.log("格式化后的行程内容（与表单匹配）：", formattedContents);

        // 4. 先清空原有内容，再赋值（解决Vue响应式问题，借鉴行程管理的数组更新逻辑）
        this.dialogForm.itineraryContents = [];
        this.$nextTick(() => {
          // 确保DOM更新后再赋值
          // 5. 合并主表数据和内容列表（完全借鉴行程管理的表单赋值方式）
          this.dialogForm = {
            ...mainData, // 主表字段（行程库名称、创建人等）
            itineraryContents:
              formattedContents.length > 0
                ? formattedContents
                : [
                    {
                      itineraryContentId: null,
                      itineraryId: itineraryId,
                      itineraryContentName: 1,
                      travelDurationNumber: null,
                      travelDurationUnit: null,
                      itineraryContent: null,
                      picture1: null,
                      picture2: null,
                      picture3: null,
                      remark: null,
                    },
                  ],
          };
          // 强制触发视图更新（解决数据变化但视图不刷新的问题）
          this.$forceUpdate();
        });

        this.open = true;
        this.title = this.isDetailMode ? "行程库详情" : "修改行程库";
        this.loading = false;
      } catch (error) {
        console.error("加载详情失败:", error);
        this.$message.error("加载详情失败，请重试");
        this.loading = false;
      }
    },

    /** 提交表单 */
    submitDialogForm() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;

        // 过滤无效内容项
        const validContents = this.dialogForm.itineraryContents.filter(
          (content) =>
            content.travelDurationNumber !== null &&
            content.travelDurationUnit &&
            content.itineraryContent
        );

        if (validContents.length === 0) {
          this.$message.error("至少需要添加一条有效的行程内容");
          return;
        }

        // 准备提交数据
        const submitData = {
          ...this.dialogForm,
          itineraryContents: validContents,
          createBy: this.currentUser?.userName || "system",
          updateBy: this.currentUser?.userName || "system",
        };

        try {
          if (submitData.itineraryId) {
            // 修改操作
            await delAllItineraryContent(submitData.itineraryId);
            await batchSaveItineraryContent(validContents);
            await updateItinerary(submitData);
            this.$message.success("修改成功");
          } else {
            // 新增操作
            const mainResult = await addItinerary(submitData);
            const itineraryId = mainResult.data?.itineraryId;
            if (!itineraryId) {
              throw new Error("新增失败，后端未返回行程ID");
            }
            // 关联行程ID后保存内容
            await batchSaveItineraryContent(
              validContents.map((item) => ({ ...item, itineraryId }))
            );
            this.$message.success("新增成功");
          }
          this.open = false;
          this.getList();
        } catch (error) {
          console.error("提交失败:", error);
          this.$message.error(
            "操作失败：" + (error.response?.data?.msg || error.message)
          );
        }
      });
    },

    /** 删除按钮事件 */
    handleDelete(row) {
      debugger;
      // const itineraryIds = row ? [row.itineraryId] : this.ids;

      const itineraryIds = row.itineraryId || this.ids;

      // if (!itineraryIds.length) {
      //   this.$message.warning("请选择至少一条记录");
      //   return;
      // }

      this.$confirm(`确定要删除选中的${itineraryIds.length}条记录吗？`)
        .then(async () => {
          await delItinerary(itineraryIds);
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },


    /** 取消按钮事件 */
    cancel() {
      this.open = false;
      this.resetDialogForm();
    },

    /** 重置对话框表单 */
    resetDialogForm() {
      this.dialogForm = {
        itineraryId: null,
        itineraryName: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null,
        remark: null,
        isDeleted: 0,
        itineraryContents: [
          {
            itineraryContentId: null,
            itineraryId: null,
            itineraryContentName: 1, // 修正为字符串类型
            travelDurationNumber: null,
            travelDurationUnit: null,
            itineraryContent: null,
            picture1: null,
            picture2: null,
            picture3: null,
            remark: null,
          },
        ],
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },

    /** 添加新内容 */
    addNewContent() {
      console.log("添加前长度：", this.dialogForm.itineraryContents.length);
      const lastIndex = this.dialogForm.itineraryContents.length - 1;
      if (!this.isContentValid(lastIndex)) {
        this.$message.warning("请先完成当前内容的必填项");
        return;
      }

      // 关键修改：创建全新的独立对象，所有属性初始化为null或基础类型
      const newContent = {
        itineraryContentId: null, // 全新ID（null）
        itineraryId: this.dialogForm.itineraryId || null, // 仅关联当前行程库ID
        itineraryContentName: (
          this.dialogForm.itineraryContents.length + 1
        ).toString(), // 独立序号
        travelDurationNumber: null, // 基础类型，无引用问题
        travelDurationUnit: null, // 独立选择
        itineraryContent: null, // 独立文本
        picture1: null, // 独立图片（初始null，不继承前项）
        picture2: null,
        picture3: null,
        remark: null, // 独立备注
      };

      // 推入全新对象（确保与前项无任何引用关联）
      this.dialogForm.itineraryContents.push(newContent);
      console.log("添加后长度：", this.dialogForm.itineraryContents.length);
      // 滚动到新增内容
      setTimeout(() => {
        const element = document.getElementById(
          `content-${this.dialogForm.itineraryContents.length - 1}`
        );
        if (element) element.scrollIntoView({ behavior: "smooth" });
      }, 100);
    },

    /** 删除内容项 */
    deleteContent(index) {
      this.$confirm(`确定要删除第${index + 1}条内容吗？`)
        .then(() => {
          this.dialogForm.itineraryContents.splice(index, 1);
          // 更新序号
          this.dialogForm.itineraryContents.forEach((item, i) => {
            item.itineraryContentName = (i + 1).toString(); // 修正为字符串类型
          });
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },

    /** 验证内容项是否完整 */
    isContentValid(index) {
      const content = this.dialogForm.itineraryContents[index];
      return (
        !!content.travelDurationNumber &&
        !!content.travelDurationUnit &&
        !!content.itineraryContent
      );
    },

    /** 图片上传成功事件 */
    handleImageSuccess(response, index, picIndex) {
      if (response.code === 200 && response.url) {
        this.dialogForm.itineraryContents[index][`picture${picIndex}`] =
          response.url;
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败：" + (response.msg || "未知错误"));
      }
    },

    /** 图片上传前验证 */
    beforeImageUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) this.$message.error("只能上传图片文件！");
      if (!isLt2M) this.$message.error("图片大小不能超过2MB！");
      return isImage && isLt2M;
    },
  },
};
</script>

<style scoped>
.dynamic-content-wrapper {
  margin: 15px 0;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.content-item {
  padding: 10px 0;
}

.mb4 {
  margin-bottom: 16px;
}

.content-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

/* 图片上传样式 */
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
/* 响应式调整 */
@media (max-width: 768px) {
  .el-row {
    flex-direction: column;
  }
  .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
}
</style>
